<template>
  <div class="route-page box">
    <section class="header">
      <a-page-header title="费用类型设置">
        <div>
          用户可以根据自身业务需求自定义不同的费用类型，还可以将同类型的费用放至同一指定分类下，以便更好地进行费用管理。
        </div>
      </a-page-header>
    </section>
    <section class="content">
      <a-card
          class="content-card"
          :bodyStyle="{
          padding: 0,
          width: '100%',
          display: 'flex',
        }"
      >
        <div class="left">
          <section style="height: 78px; padding: 0 10px">
            <div
                style="
                color: rgba(0, 0, 0, 0.85);
                font-weight: 600;
                font-size: 16px;
              "
            >
              费用分类
            </div>
            <a-input-search
                v-model:value="cateKeywords"
                placeholder="请输入分类"
                enter-button
                @search="getCateList"
                allowClear
                style="margin: 10px 0"
            />
          </section>
          <section class="cate-list-wrap">
            <div class="cate-list hide-scroller-bar">
              <li
                  class="cate-list-item"
                  @click="onCateClick(cateAll)"
                  :class="
                  currentCate.id == cateAll.id ? 'cate-list-item-current' : ''
                "
                  v-if="showCheckAll"
              >
                <span>{{ cateAll.name }}</span>
              </li>
              <template v-if="cateList.length > 0">
                <draggable
                    group="dragList"
                    v-model="cateList"
                    v-bind="dragOptions"
                    item-key="id"
                    @end="onDragFinish"
                >
                  <template #item="{ element }">
                    <li
                        class="cate-list-item"
                        @click="onCateClick(element)"
                        :class="
                        currentCate.id == element.id
                          ? 'cate-list-item-current'
                          : ''
                      "
                    >
                      <span>{{ element.name }}</span>
                      <div class="right-icons">
                        <unordered-list-outlined/>
                        <a-dropdown :trigger="['click']" v-if="!element.is_root">
                        <span
                            class="ant-dropdown-link"
                            @click.stop
                            style="padding: 0 5px"
                        >
                          <MoreOutlined/>
                        </span>
                          <template #overlay>
                            <a-menu>
                              <a-menu-item key="0">
                                <a-button
                                    type="link"
                                    style="
                                  width: 100%;
                                  text-align: center;
                                  padding: 0 16px;
                                  margin: 0;
                                "
                                    @click="editCate(element.id)"
                                >编辑
                                </a-button
                                >
                              </a-menu-item>
                              <a-menu-item key="1">
                                <a-button
                                    type="link"
                                    danger
                                    style="
                                  width: 100%;
                                  text-align: center;
                                  padding: 0 16px;
                                  margin: 0;
                                "
                                    @click="deleteCate(element.id)"
                                >删除
                                </a-button
                                >
                              </a-menu-item>
                            </a-menu>
                          </template>
                        </a-dropdown>
                      </div>
                    </li>
                  </template>
                </draggable>
              </template>
            </div>
            <!-- 底部操作按钮 -->
            <a-card size="small" :bordered="false" class="footer-btn">
              <a-button
                  type="primary"
                  ghost
                  @click="editCate"
                  style="width: 100%"
              >
                <template #icon>
                  <PlusOutlined/>
                </template>
                新建分类
              </a-button>
            </a-card>
          </section>
        </div>
        <div class="right">
          <a-row align="middle" justify="space-between">
            <a-col>
              <a-input-search
                  v-model:value="keywords"
                  placeholder="请输入费用名称"
                  enter-button
                  @search="getList"
                  allowClear
              />
            </a-col>
            <a-col>
              <a-space>
                <a-button
                    v-if="$store.getters.userInfo.org_id == 1689"
                    @click="goCoupon"
                >
                  优惠券管理
                </a-button>
                <a-button type="primary" @click="editClick()">
                  <PlusOutlined/>
                  新建费用类型
                </a-button>
              </a-space>
            </a-col>
          </a-row>
          <a-table
              :dataSource="dataSource"
              :columns="columns"
              :pagination="pagination"
              @change="handleTableChange"
              rowKey="id"
              :bordered="true"
              size="small"
              style="margin-top: 5px"
              :scroll="{ y: tableScrollHeight }"
              class="fee-type-table"
          >
            <template #headerCell="{ title, column }">
              <template v-if="column.key === 'is_important'">
                <span> 特别重要 </span>
                <text-tip
                    tips="特别重要的费用类型，若欠费将会影响业务的使用。例如门锁、人脸门禁等将会失效。移动端自主缴费时，此项会自动勾选，必须缴纳。"
                />
              </template>
            </template>
            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key === 'is_important'">
                <a-tag :color="text?'red':''"> {{text ?'是':'否'}}</a-tag>
              </template>
              <template v-if="column.key === 'status'">
                <a-switch
                    v-model:checked="record.status"
                    :checkedValue="1"
                    :unCheckedValue="0"
                    @change="(checked) => onStatusTrigger(checked, record)"
                />
              </template>
              <template v-if="column.key === 'action'">
                <a-button
                    type="link"
                    style="padding: 0; margin: 0"
                    @click.stop="editClick(record.id, record.is_root)"
                >编辑
                </a-button
                >
                <a-tooltip>
                  <template #title>系统内置费用类型不可删除</template>
                  <a-button
                      type="link"
                      danger
                      style="padding: 0; margin-right: 0; margin-left: 10px"
                      v-if="record.is_root"
                  >删除
                  </a-button
                  >
                </a-tooltip>
                <a-button
                    v-if="!record.is_root"
                    type="link"
                    danger
                    style="padding: 0; margin-right: 0; margin-left: 10px"
                    @click.stop="deleteClick(record.id)"
                >删除
                </a-button
                >
              </template>
            </template>
          </a-table>
        </div>
      </a-card>
    </section>

    <!-- 新增、编辑分类 -->
    <EditCategory
        :visible="editCateVisible"
        :id="editCateId"
        @onClose="editCateVisible = false"
        @success="onEditCateSuccess"
    />

    <!-- 新增、编辑费用类型 -->
    <EditFeeType
        :visible="editVisible"
        :id="editId"
        :is_root="is_root"
        :cateId="currentCate.id"
        @onClose="editVisible = false"
        @success="onEditSuccess"
    />
  </div>
</template>

<script>
import {
  defineComponent,
  onBeforeUnmount,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
  computed,
  createVNode,
  nextTick,
} from "vue";
import {useRouter, useRoute} from "vue-router";
import {
  MoreOutlined,
  PlusOutlined,
  ExclamationCircleOutlined,
  UnorderedListOutlined,
} from "@ant-design/icons-vue";
import {Form, message, Modal} from "ant-design-vue";
import store from "../../../store";
import request from "../../../common/utils/request";
import draggable from "vuedraggable";
import EditCategory from "./module/EditCategory.vue";
import EditFeeType from "./module/EditFeeType.vue";
import {TextTip} from "bl-common-vue3";


export default defineComponent({
  name: "FeeTypeSetting",
  components: {
    MoreOutlined,
    draggable,
    PlusOutlined,
    EditCategory,
    EditFeeType,
    TextTip,
    UnorderedListOutlined
  },
  setup() {
    const $router = useRouter();
    const state = reactive({
      cateKeywords: "",
      cateList: [], //费用分类列表
      currentCate: {
        name: "所有",
        id: 0,
      },
      cateAll: {
        name: "所有",
        id: 0,
      },
      showCheckAll: true,
      editCateVisible: false,
      editCateId: null,

      keywords: "",
      dataSource: [], //费用类型列表
      total: 0,
      page: 1,
      pageSize: 20,
      columns: [
        {
          title: "费用名称",
          dataIndex: "name",
          width: "20%",
          align: "center",
        },
        {
          title: "所属分类",
          dataIndex: "category_name",
          width: "20%",
          align: "center",
        },
        {
          title: "特别重要",
          dataIndex: "is_important",
          key: "is_important",
          width: "10%",
          align: "center",
        },
        {
          title: "排序",
          dataIndex: "sort",
          width: "20%",
          align: "center",
        },
        {
          title: "状态",
          width: "10%",
          dataIndex: "status",
          key: "status",
          align: "center",
        },
        {
          title: "操作",
          dataIndex: "id",
          key: "action",
          width: "20%",
          align: "center",
        },
      ],
      editVisible: false,
      editId: null,

      tableScrollHeight: null,
      is_root: 0,
    });

    const getCateList = () => {
      let params = {
        setting: 1
      };

      if (state.cateKeywords) {
        params.keyword = state.cateKeywords;
      }

      request
          .get("/org", "/bill/cost/categoryList", {...params})
          .then((res) => {
            if (res.list) {
              state.cateList = res.list;
              if (state.cateKeywords) {
                state.showCheckAll = false;
              } else {
                state.showCheckAll = true;
                state.currentCate = state.cateAll;

                state.page = 1;
                state.pageSize = 20;
                getList();
              }
            }
          });
    };

    const onCateClick = (item) => {
      if (state.currentCate.id == item.id) {
        return;
      }
      state.page = 1;
      state.currentCate = item;
      getList();
    };

    const editCate = (id) => {
      state.editCateId = 0;
      if (id && id > 0) {
        state.editCateId = id;
      }
      state.editCateVisible = true;
    };

    const deleteCate = (id) => {
      Modal.confirm({
        title: () => `确定要删除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
              .del("/org", "/bill/cost/categoryDel", {
                id,
              })
              .then((res) => {
                message.success("删除成功");
                store.dispatch("RemoveTemplateInit").then(() => {
                  store.dispatch("RemoveContractInit").then(() => {
                    getCateList();
                  });
                });
              });
        },
      });
    };

    const onEditCateSuccess = () => {
      state.editCateVisible = false;
      getCateList();
    };

    const init = () => {
      getCateList();
    };

    init();

    const dragOptions = computed(() => {
      return {
        animation: 200,
        group: "description",
        disabled: false,
        ghostClass: "ghost",
      };
    });

    let dragTimer = null;
    const onDragFinish = (e) => {
      if (dragTimer) {
        clearTimeout(dragTimer);
        dragTimer = null;
      }
      dragTimer = setTimeout(() => {
        let result = state.cateList.map((item, index) => ({
          id: item.id,
          sort: index + 1,
        }));
        request
            .put("/org", "/bill/cost/categorySort", {list: result})
            .then((res) => {
            });
      }, 500);
    };

    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));

    const handleTableChange = (pager, filters, sorter) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      getList();
    };

    const getList = () => {
      let params = {
        page: state.page,
        limit: state.pageSize,
      };

      if (state.currentCate && state.currentCate.id) {
        params.category_id = state.currentCate.id;
      }

      if (state.keywords) {
        params.keyword = state.keywords;
      }

      request.get("/org", "/bill/costList", {...params}).then((res) => {
        if (res.list) {
          state.dataSource = res.list;
        }
        state.total = res.total;

        nextTick(() => {
          let tableList = document.getElementsByClassName("fee-type-table");
          if (tableList && tableList.length > 0) {
            state.tableScrollHeight = tableList[0].offsetHeight - 100;
          }
          console.log(state.tableScrollHeight);
        });
      });
    };

    const editClick = (id, is_root) => {
      state.editId = 0;
      if (id && id > 0) {
        state.editId = id;
      }
      state.is_root = is_root;
      state.editVisible = true;
    };

    const deleteClick = (id) => {
      Modal.confirm({
        title: () => `确定要删除吗？`,
        icon: () => createVNode(ExclamationCircleOutlined),
        centered: true,
        onOk() {
          request
              .del("/org", "/bill/billCostDel", {
                id,
              })
              .then((res) => {
                message.success("删除成功");
                store.dispatch("RemoveTemplateInit").then(() => {
                  store.dispatch("RemoveContractInit").then(() => {
                    getList();
                  });
                });
              });
        },
      });
    };

    const onEditSuccess = () => {
      state.editVisible = false;
      getList();
    };

    const onStatusTrigger = (checked, record) => {
      request
          .put("/org", "/bill/costStatus", {
            id: record.id,
            status: checked,
          })
          .then((res) => {
            message.success("操作成功");
            store.dispatch("RemoveTemplateInit").then(() => {
              store.dispatch("RemoveContractInit").then(() => {
                getList();
              });
            });
          });
    };

    const goCoupon = () => {
      $router.push({name: "couponManagement"});
    };

    return {
      ...toRefs(state),
      onCateClick,
      getCateList,
      dragOptions,
      onDragFinish,
      editCate,
      deleteCate,
      onEditCateSuccess,

      pagination,
      handleTableChange,
      getList,
      editClick,
      deleteClick,
      onEditSuccess,
      onStatusTrigger,
      goCoupon,
    };
  },
});
</script>

<style lang="less" scoped>
.header {
  background: #fff;
  margin-left: 1px;

  &:deep(.ant-tabs-bar) {
    margin: 0;
  }
}

.content {
  flex: 1;
  padding: 10px;
  height: calc(100% - 94px);

  .content-card {
    width: 100%;
    height: 100%;
    display: flex;

    .left {
      width: 220px;
      height: 100%;
      border-right: 1px solid #f1f1f1;
      padding-top: 20px;

      .cate-list-wrap {
        height: calc(100% - 78px);
        position: relative;

        .footer-btn {
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          background-color: #fff;
          box-shadow: -2px 0 8px #0000001a;
        }

        .cate-list {
          height: 100%;
          overflow: hidden auto;
          padding: 0 10px 70px 10px;

          .cate-list-item {
            padding: 5px 0 5px 10px;
            margin-top: 5px;
            border-radius: 4px;
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
          }

          .cate-list-item:hover {
            background-color: #e6f3fb;
          }

          .right-icons {
            font-size: 12px;
            display: flex;
            align-items: center;
            width: 35px;
          }

          .cate-list-item-current {
            background-color: #cceaff;
          }
        }
      }
    }

    .right {
      width: calc(100% - 220px);
      padding: 20px 10px;

      .fee-type-table {
        width: 100%;
        height: calc(100% - 52px);
      }
    }
  }
}
</style>
